package top.frsf.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import top.frsf.reggie.dto.SetmealDto;
import top.frsf.reggie.entity.SetmealDish;
import top.frsf.reggie.excpetion.BusinessException;
import top.frsf.reggie.mapper.SetmealMapper;
import top.frsf.reggie.entity.Setmeal;
import top.frsf.reggie.service.DishService;
import top.frsf.reggie.service.SetmealDishService;
import top.frsf.reggie.service.SetmealService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 套餐(Setmeal)表服务实现类
 *
 * @author makejava
 * @since 2023-01-15 00:37:32
 */
@Service("setmealService")
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * @Author: FRSF
     * @Date: 2023/1/28 17:12
     * @Description 新增套餐，同时需要保存套餐与菜品之间的关系
     * @param setmealDto:
     * @return: void
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        // 保持套餐的基本信息，操作setmeal，执行insert
        this.save(setmealDto);

        // 保存套餐和菜品的关联信息，操作setmeal_dish，执行insert
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/28 19:41
     * @Description 批量删除套餐，且关联菜品进行删除
     * @param ids:
     * @return: void
     */
    @Override
    public void removeWithDish(List<Long> ids) {
        // 查询套餐信息，判断是否起售从而可以删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, ids);
        wrapper.eq(Setmeal::getStatus, 1);
        long count = this.count(wrapper);

        if (count > 0) {
            // 不能删除，抛出业务异常
            throw new BusinessException("套餐正在售卖中，不能直接删除");
        } else {
            // 可以删除，删除套餐表中的数据
            this.removeByIds(ids);
        }

        // 删除关联表信息setmeal_dish
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }


}

